#include "userproxyimp.h"
#include "logindialog.h"
#include "registerdialog.h"
#include <sailmipim/core/icoreproxy.h>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonObject>
#include <QJsonDocument>
#include <QUrl>
/**
 *Basic c2FpbG1pcGltOnBpbV9zZWNAU00wMTA1
 *http://api.sailmi.com:16800/auth-service/token
 *返回结果：
 *{
    "code": 200,
    "success": true,
    "data": {
        "accessToken": "eyJ0eXAiOiJKc29uV2ViVG9rZW4iLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1c2VyIiwiYXVkIjoiYXVkaWVuY2UiLCJpYXQiOjE3MzcyOTI0NDAsInJvbGVfbmFtZSI6IiIsInVzZXJfY29kZSI6IjhhOWFhMWRkNWE4ZWFhMjEwMTVhOTFlMDBkZTEwMDc0IiwidXNlcl9pZCI6IjEiLCJ1c2VyX25hbWUiOiIiLCJ0b2tlbl90eXBlIjoiYWNjZXNzX3Rva2VuIiwiZW50ZXJwcmlzZV9pZCI6IiIsImFjY291bnQiOiJhZG1pbiIsImNsaWVudF9pZCI6InNhaWxtaXBpbSIsImV4cCI6MTczNzI5NjA0MCwibmJmIjoxNzM3MjkyNDQwfQ.YhoArzvF31HhFc8YCWXLTqB_rU8OR5ERrHTFYPO580Q",
        "tokenType": "bearer",
        "refreshToken": "eyJ0eXAiOiJKc29uV2ViVG9rZW4iLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1c2VyIiwiYXVkIjoiYXVkaWVuY2UiLCJpYXQiOjE3MzcyOTI0NDAsInVzZXJfaWQiOiIxIiwidG9rZW5fdHlwZSI6InJlZnJlc2hfdG9rZW4iLCJjbGllbnRfaWQiOiJzYWlsbWlwaW0iLCJleHAiOjE3Mzc4OTcyNDAsIm5iZiI6MTczNzI5MjQ0MH0.Z8tdRf3HZ-7e9j4ruidj-Jf0ueXqwTIfVYN6cNFHPCs",
        "avatar": "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png",
        "authority": "",
        "userName": "",
        "userCode": "8a9aa1dd5a8eaa21015a91e00de10074",
        "account": "admin",
        "expiresIn": 0,
        "license": "powered by sailmi",
        "tenantId": "000000",
        "grantType": "password",
        "password": "",
        "authUser": null,
        "clientId": null
    },
    "msg": "操作成功"
}
 */
namespace SailmiPIM::Plugin::UserProxy
{
UserProxyImp::UserProxyImp(QObject *parent)
{
    qDebug()<<"UserProxyImp::UserProxyImp:Create A User Proxy Implements!";
}
UserInfo* UserProxyImp::login(QString userName,QString userPass){
    QNetworkAccessManager *netManager=GetProxyHolder()->GetNetworkAccessManager();
    QEventLoop eventLoop;
    connect(netManager,SIGNAL(finished(QNetworkReply*)),&eventLoop,SLOT(quit()));
    QNetworkRequest *apiRequest=new QNetworkRequest(QUrl(apiTokenUrl));
    apiRequest->setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    apiRequest->setRawHeader(QByteArray("Authorization"),"Basic c2FpbG1pcGltOnBpbV9zZWNAU00wMTA1"); //客户终端授权
    // 准备要发送的数据
    QByteArray postData;
    postData.append("account=");
    postData.append(userName.toUtf8());
    postData.append("&");
    postData.append("password=");
    postData.append(userPass.toUtf8());
    QNetworkReply *reply = netManager->post(*apiRequest,postData);
    eventLoop.exec();
    QByteArray responseData = reply->readAll();
    //解析返回结果
    UserInfo *userInfo = parseUserTokenJson(QString(responseData));
    if(userInfo!=NULL){
        userInfo->isLogined = true;
    }
    return userInfo;
}

QDialog* UserProxyImp::getLoginDialog(QWidget *parent,UserInfo *luserInfo){
    LoginDialog *loginDialog  = new LoginDialog(parent);
    luserInfo->isLogined = true;
    return loginDialog;
}
QDialog* UserProxyImp::getRegisterDialog(QWidget *parent,UserInfo *ruserInfo){
    RegisterDialog *registerDialog = new RegisterDialog(parent);
    ruserInfo->isRegistered = true;
    return registerDialog;
}

/**
 * @brief UserProxyImp::parseUserJson
 * @param userJson
 * @return
 *  *{
    "code": 200,
    "success": true,
    "data": {
        "accessToken": "eyJ0eXAiOiJKc29uV2ViVG9rZW4iLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1c2VyIiwiYXVkIjoiYXVkaWVuY2UiLCJpYXQiOjE3MzcyOTI0NDAsInJvbGVfbmFtZSI6IiIsInVzZXJfY29kZSI6IjhhOWFhMWRkNWE4ZWFhMjEwMTVhOTFlMDBkZTEwMDc0IiwidXNlcl9pZCI6IjEiLCJ1c2VyX25hbWUiOiIiLCJ0b2tlbl90eXBlIjoiYWNjZXNzX3Rva2VuIiwiZW50ZXJwcmlzZV9pZCI6IiIsImFjY291bnQiOiJhZG1pbiIsImNsaWVudF9pZCI6InNhaWxtaXBpbSIsImV4cCI6MTczNzI5NjA0MCwibmJmIjoxNzM3MjkyNDQwfQ.YhoArzvF31HhFc8YCWXLTqB_rU8OR5ERrHTFYPO580Q",
        "tokenType": "bearer",
        "refreshToken": "eyJ0eXAiOiJKc29uV2ViVG9rZW4iLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1c2VyIiwiYXVkIjoiYXVkaWVuY2UiLCJpYXQiOjE3MzcyOTI0NDAsInVzZXJfaWQiOiIxIiwidG9rZW5fdHlwZSI6InJlZnJlc2hfdG9rZW4iLCJjbGllbnRfaWQiOiJzYWlsbWlwaW0iLCJleHAiOjE3Mzc4OTcyNDAsIm5iZiI6MTczNzI5MjQ0MH0.Z8tdRf3HZ-7e9j4ruidj-Jf0ueXqwTIfVYN6cNFHPCs",
        "avatar": "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png",
        "authority": "",
        "userName": "",
        "userCode": "8a9aa1dd5a8eaa21015a91e00de10074",
        "account": "admin",
        "expiresIn": 0,
        "license": "powered by sailmi",
        "tenantId": "000000",
        "grantType": "password",
        "password": "",
        "authUser": null,
        "clientId": null
    },
    "msg": "操作成功"
 */
UserInfo* UserProxyImp::parseUserTokenJson(QString userJson){
    qDebug() << Q_FUNC_INFO << userJson;
    if(userJson.isEmpty()) return NULL;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(userJson.toUtf8());
    if(!jsonDoc.isObject()){
        qDebug() << Q_FUNC_INFO << "Login Response Json Root Error!";
        return NULL;
    }
    QJsonObject rootObj=jsonDoc.object();
    QJsonObject dataObj = rootObj["data"].toObject();
    int requestCode = rootObj["code"].toInt();
    if(requestCode!=200){
        qDebug() << Q_FUNC_INFO << "Login Request Server Internal  Error!";
        return NULL;

    }
    if(dataObj.isEmpty()){
        qDebug() << Q_FUNC_INFO << "Login Response Json Data Error!";
        return NULL;
    }
    UserInfo *userInfo=new UserInfo();
    userInfo->isLogined = true;
    userInfo->userAvatar = dataObj["avatar"].toString();
    userInfo->userName = dataObj["userName"].toString();
    userInfo->userAccount =dataObj["account"].toString();
    userInfo->userToken=dataObj["accessToken"].toString();
    userInfo->userNick=dataObj["userName"].toString();
    userInfo->userRight = dataObj["authority"].toString();
    return userInfo;
}




UserInfo* UserProxyImp::registerUser(UserInfo *userInfo){
    qDebug() << Q_FUNC_INFO << "Start Register User!";
    QNetworkAccessManager *netManager=GetProxyHolder()->GetNetworkAccessManager();
    qDebug() << Q_FUNC_INFO << "Start Request NetManager!";
    qDebug() << Q_FUNC_INFO << "Start Request NetManager!"<<" aaaaaaaaaaaaaaaaaaaaaaa";
    qDebug() << Q_FUNC_INFO << "Start Request NetManager!"<<apiTokenUrl.toUtf8();
    qDebug() << Q_FUNC_INFO << "Start Request NetManager!"<<apiRegisterUrl.toUtf8();
    QEventLoop eventLoop;
    connect(netManager,SIGNAL(finished(QNetworkReply*)),&eventLoop,SLOT(quit()));
    qDebug() << Q_FUNC_INFO << "Start connect NetManager!";
    QNetworkRequest *apiRequest=new QNetworkRequest(QUrl(apiRegisterUrl));
    qDebug() << Q_FUNC_INFO << "Start Request Url!";
    apiRequest->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    apiRequest->setRawHeader(QByteArray("Authorization"),"Basic c2FpbG1pcGltOnBpbV9zZWNAU00wMTA1"); //客户终端授权
    qDebug() << Q_FUNC_INFO << "Start set header!";

    // 准备要发送的数据
    QJsonObject postObj;
    postObj.insert("clientId","sailmipim");
    postObj.insert("userId",0);
    postObj.insert("userCode",userInfo->userName);
    postObj.insert("tenantId","000000");
    postObj.insert("enterprise","000000");
    postObj.insert("userName",userInfo->userName);
    postObj.insert("account",userInfo->userName);
    postObj.insert("password",userInfo->userPass);
    postObj.insert("nickName",userInfo->userNick);
    postObj.insert("phone",userInfo->userPhone);
    postObj.insert("avatar",userInfo->userAvatar);
    QJsonDocument postDoc(postObj);
    qDebug() << Q_FUNC_INFO << postDoc.toJson();
    QByteArray postData =  postDoc.toJson(QJsonDocument::Compact);
    QNetworkReply *reply = netManager->post(*apiRequest,postData);
    qDebug() << Q_FUNC_INFO << "Start post data!";

    eventLoop.exec();
    QByteArray responseData = reply->readAll();
    QString responseStr = QString(responseData);
    qDebug() << Q_FUNC_INFO << responseStr;
    //解析返回结果
    UserInfo *userInfoRet = parseUserAuthJson(responseStr);
    if(userInfoRet!=NULL){
        userInfoRet->isRegistered = true;
        userInfoRet->isLogined = true;
        qDebug() << Q_FUNC_INFO << "Register User End!";
    }
    return userInfoRet;

}

/**
 * {\"code\":200,
 *  \"success\":true,
 *  \"data\":{\"clientId\":\"sailmipim\",
 *            \"userId\":0,\"userCode\":\"5\",
 *            \"tenantId\":\"000000\",
 *            \"enterprise\":null,
 *            \"userName\":\"5\",
 *            \"account\":\"5\",
 *            \"password\":\"5\",
 *            \"nickName\":\"5\",
 *            \"roleId\":null,
 *            \"roles\":null,
 *            \"permissions\":null,
 *            \"expiresIn\":0,
 *            \"phone\":\"5\",
 *            \"avatar\":\"\",
 *            \"roleName\":null,
 *            \"userInfoMap\":{},
 *            \"initpass\":false
 *           },
 *  \"msg\":\"操作成功\"}
 * @brief UserProxyImp::parseUserAuthJson
 * @param userJson
 * @return
 */

UserInfo* UserProxyImp::parseUserAuthJson(QString userJson){
    qDebug() << Q_FUNC_INFO << userJson;
    if(userJson.isEmpty()) return NULL;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(userJson.toUtf8());
    if(!jsonDoc.isObject()){
        qDebug() << Q_FUNC_INFO << "Login Response Json Root Error!";
        return NULL;
    }
    QJsonObject rootObj=jsonDoc.object();
    QJsonObject dataObj = rootObj["data"].toObject();
    int requestCode = rootObj["code"].toInt();
    if(requestCode!=200){
        qDebug() << Q_FUNC_INFO << "Login Request Server Internal  Error!";
        return NULL;

    }
    if(dataObj.isEmpty()){
        qDebug() << Q_FUNC_INFO << "Login Response Json Data Error!";
        return NULL;
    }
    UserInfo *userInfo=new UserInfo();
    userInfo->isLogined = false;
    userInfo->isRegistered = true;
    userInfo->userName = dataObj["userName"].toString();
    userInfo->userAvatar =dataObj["avatar"].toString();
    userInfo->userAccount = dataObj["account"].toString();
    userInfo->userPhone =  dataObj["phone"].toString();
    userInfo->userNick=dataObj["nickName"].toString();
    userInfo->userRight = dataObj["permissions"].toString();
    return userInfo;
}

}
